﻿Imports OpenTK.Graphics.OpenGL

Module FrameBuffer
    Public fbo As Integer
    Public color As Integer
    Private width As Integer
    Private height As Integer

    Public Sub CreateFrameBufferObject(w As Integer, h As Integer)
        width = w : height = h
        color = GL.GenRenderbuffer()
        GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, color)
        REM 数据类型要受支持，例如RenderbufferStorage.Rgba32i是一般不受支持的,而且I U后缀不支持多重采样
        GL.RenderbufferStorageMultisample(RenderbufferTarget.Renderbuffer, 0, RenderbufferStorage.Rgba8, width, height)

        fbo = GL.GenFramebuffer()
        GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo)
        GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, RenderbufferTarget.Renderbuffer, color)

        Dim status As FramebufferErrorCode = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer)
        If status <> FramebufferErrorCode.FramebufferComplete Then
            Throw New Exception("FBO Error:" + status.ToString())
        End If
        GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0)
    End Sub

    Public Sub FBOBeginDraw()
        GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo)
        GL.Viewport(0, 0, width, height)
        Dim drawbuffers() As DrawBuffersEnum = {DrawBuffersEnum.ColorAttachment0}
        GL.DrawBuffers(1, drawbuffers)
    End Sub

    Public Sub FBOEndDraw()
        GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0)
        GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0)
    End Sub

    Public Sub CopyToDeviceFrameBuffer(w As Integer, h As Integer, framebuffer As Integer)
        'GL.ReadBuffer(ReadBufferMode.ColorAttachment1)
        'GL.DrawBuffer(DrawBufferMode.ColorAttachment1)
        GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, framebuffer)
        GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, 0)
        GL.BlitFramebuffer(0, 0, width, height, 0, 0, w, h, ClearBufferMask.ColorBufferBit, BlitFramebufferFilter.Linear) REM 如果用到其他的bufferbit 过滤就不能用linear
    End Sub
End Module
